(function () {
    // 参数转换
    var transform = function (data) {
        var params = [];
        for (let key in data) {
            params.push(key + '=' + data[key]);
        }
        return params.join('&');
    }
    var XHR;
    // 初始化分支
    if (window.XMLHttpRequest) {
        XHR = function () {
            return new XMLHttpRequest();
        }
    } else {
        XHR = function () {
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    // 请求函数
    var request = function (options) {
        var xhr = XHR();
        xhr.onreadystatechange = function (e) {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    var data = JSON.parse(xhr.responseText);
                    options.success(data, xhr);
                } else {
                    var error = "错误状态：" + xhr.status + "\n错误信息：" + xhr.statusText;
                    options.error(error, xhr);
                }
            }
        }
        if (options.type == 'get') {
            xhr.open('get', options.url +'?'+ options.data, true);
            xhr.send(null);
            return;
        }
        if (options.type == 'post') {
            xhr.open('post', options.url, true);
            xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
            xhr.send(options.data);
        }
    }
    // 外部定义
    window._ = {
        ajax: function (options) {
            request({
                url: options.url || "",
                type: options.type || "get",
                data: transform(options.data),
                success: options.success || function (data) { },
                error: options.error || function (error) { }
            })
        },
        get: function (url, data, fn) {
            _.ajax({ url: url, data: data, success: fn })
        },
        post: function (url, data, fn) {
            _.ajax({ url: url, type: 'post', data: data, success: fn })
        }
    }
})();